﻿using System;
using System.Web.Mvc;
using Olemas.DataModels;

namespace Olemas.Controllers
{
    public class DetailsController : Controller
    {

        //
        // GET: /Details/Book/2

        /// <summary>
        /// Sends the book specified by the Id to the view.
        /// </summary>
        /// <param name="id">The id of the book to display details for.</param>
        public ActionResult Book(int id)
        {

            var book = BookModel.GetBookById(id);
            if (book == null)
            {
                return HttpNotFound();
            }
            return View("BookDetails", book);
        }

        /// <summary>
        /// Sends the conspect specified by the Id to the view.
        /// </summary>
        /// <param name="id">The id of the conspect to display details for.</param>
        public ActionResult Conspect(int id)
        {
            var conspect = ConspectModel.GetConspectById(id);
            if (conspect == null)
            {
                return HttpNotFound();
            }
            return View("ConspectDetails", conspect);
        }

        /// <summary>
        /// Sends the test specified by the Id to the view.
        /// </summary>
        /// <param name="id">The id of the test to display details for.</param>
        public ActionResult Test(int id)
        {
            var test = TestModel.GetTestById(id);
            if (test == null)
            {
                return HttpNotFound();
            }
            return View("TestDetails", test);
        }

        /// <summary>
        /// Sends the requested file to the browser.
        /// </summary>
        /// <param name="id">The id of the file to be downloaded.</param>
        public ActionResult DownloadConspect(int id)
        {
            var file = ConspectModel.GetConspectFileById(id);

            // Checks if the file is in the database
            if (file == null)
            {
                // TODO: logida faili puudumine
                return new HttpNotFoundResult();
            }

            var dir = Server.MapPath("~/Content/Conspect_Files/");

            var fileLocation = dir + file.Location;

            // Checks if the file is on the server
            if (!ConspectModel.CheckFile(fileLocation))
            {
                // TODO: logida faili puudumine
                return new HttpNotFoundResult();
                
            }
            var contentType = file.Type;
            Response.AddHeader("Content-Disposition", String.Format("inline;filename=\"{0}\"", file.Location));

            return File(fileLocation, contentType);
        }



    }
}
